package com.anrongtec.zcpt.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.module.AppUpgrade;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.db.LiteOrmDBUtil;
import com.art.base.util.NetUtil;
import com.art.base.util.log.LogUtil;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 检测app是否需要升级的服务
 * 
 * 定时任务发送请求检测
 * 
 */
public class AppUpgradeService extends Service {
	private static final String TAG = "AppUpgradeService";

	private static final long TIME = 10 * 60 * 1000;
	private final Timer timer = new Timer();
	private TimerTask task;
	private boolean isUploading = false;

	private ArrayList<AppModel> apps;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			// 如果有网,并且不在上传中,开始上传信息
			if (NetUtil.isNetworkAvailable(AppUpgradeService.this)) {
				if (!isUploading) {
					Util.post(new Runnable() {
						@Override
						public void run() {
							LogUtil.trace(Log.DEBUG, TAG, "getAppUpgradeInfo");
							getAppUpgradeInfo();
						}
					});

				}
			}
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		resetTimer();

		return START_STICKY;
	}

	/**
	 * 重置定时任务
	 */
	private void resetTimer() {
		if (task != null) {
			task.cancel();
		}
		task = new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(1);
			}
		};
		timer.schedule(task, 0, TIME);
	}

	/**
	 * 获取app升级信息
	 */
	private synchronized void getAppUpgradeInfo() {
		try {
			isUploading = true;
			// List<AppModel> appsInfo =
			// Util.getAppsInfo(AppUpgradeService.this);
			List<AppModel> appsInfo = Util.getAppsFromMaket(AppUpgradeService.this);
			String json = GsonUtil.toAppUpgradeJson(appsInfo);
			HttpUtil.post(json, new StoreStringCallBack(this) {
				@Override
				public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
					super.onResponse(arg0, arg1, arg2, arg3);
					Log.e("111111",arg1);
					JsonDataRestult<PageList<AppUpgrade>> result = GsonUtil.decode(arg1,
							new TypeToken<JsonDataRestult<PageList<AppUpgrade>>>() {
							}.getType());
					if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
						ArrayList<AppUpgrade> checkResut = result.getData().getCheckResut();
						if (apps == null) {
							apps = new ArrayList<AppModel>();
						} else {
							apps.clear();
						}
						if (!Util.isEmpty(checkResut)) {
							for (AppUpgrade upgrade : checkResut) {
								if (upgrade.isUpdate()) {

									AppModel queryById = LiteOrmDBUtil.getLiteOrm().queryById(upgrade.getPkg(),
											AppModel.class);

									queryById.setNeedUpgrade(true);// 需要更新
									queryById.setRemoteVersionCode(upgrade.getExpVersionCode());// 远程版本号
									queryById.setRemoteSize(upgrade.getExpSize());
									apps.add(queryById);

								}
							}
						}
						// 需要更新的信息保存到数据库
						LiteOrmDBUtil.insertAll(apps);

						// 不管有没有都发广播
						Intent intent = new Intent();
						intent.setAction(Constant.Action.APP_UPGRADE);
						// intent.putExtra(Constant.DATA_APP_UPGRADE,
						// apps.size());
						sendBroadcast(intent);
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			isUploading = false;
		}
	}

	/**
	 * 获取需要升级的应用
	 * 
	 * @return
	 */
	public static List<AppModel> getNeedUpgreade() {
		List<AppModel> queryAll = LiteOrmDBUtil.getQueryAll(AppModel.class);
		List<AppModel> temp = new ArrayList<AppModel>();
		for (AppModel appModel : queryAll) {
			if (appModel.isNeedUpgrade()) {
				temp.add(appModel);
			}
		}
		return temp;
	}

}
